package com.google.code.mc4java.conn;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.google.code.mc4java.SaeMemcachexClient;
import com.google.code.mc4java.algorithm.HashAlgorithm;

public class ConnectionManager {

	private List<SaeMemcachexClient.ServerInfo> serverLis = new CopyOnWriteArrayList<SaeMemcachexClient.ServerInfo>();
	
	private List<AbstractConnection> connList = new CopyOnWriteArrayList<AbstractConnection>();
	
	
	private HashAlgorithm algorithm = new HashAlgorithm();
	
	private ConnectionManager() {
		
	}
	
	public AbstractConnection getConnection(String key) {
		int val = algorithm.getHashValue(key, serverLis.size());
		return connList.get(val);
	}
	
	public void addServer(SaeMemcachexClient.ServerInfo server) {
		serverLis.add(server);
		connList.add(new NioConnection());
	}
	
	public void init() throws IOException {
		for(int i=0;i<serverLis.size();i++) {
			AbstractConnection ac = connList.get(i);
			ac.init(serverLis.get(i));
		}
	}
	
	public static ConnectionManager getInstance() {
		return ConnectionManager.Inner.INSTANCE;
	}
	private static class Inner {
		private static final ConnectionManager INSTANCE = new ConnectionManager();
	}
}
